package com.yuxi;

/**
 * Created by yuxi on 17/1/31.
 */
public class WaitDemo {
    public static void main(String[] args) {
        Object object = new Object();
        MyThread myThread = new MyThread(object);
        new Thread(myThread).start();
//        new Thread(myThread).start();
        //需要注意的是wait和notify都必须在synchronized里面,否则就会抛出异常
        try {
            Thread.sleep(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (object) {
            System.out.println("因为wait释放锁了所有main线程可以立刻拿到" + Thread.currentThread().getName() + "..." + System.currentTimeMillis());
            object.notify();
            System.out.println("因为wait释放锁了所有main线程可以立刻拿到" + Thread.currentThread().getName() + "..." + System.currentTimeMillis());
        }

    }


    static class MyThread implements Runnable {
        private Object object;

        public MyThread(Object object) {
            this.object = object;
        }

        public void run() {
            synchronized (object) {
                try {
                    System.out.println("wait....." + Thread.currentThread().getName() + "..." + System.currentTimeMillis());
                    object.wait();
                    Thread.sleep(2000);
                    System.out.println("wait....." + Thread.currentThread().getName() + "..." + System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}



